package mysql

import (
	"gorm.io/gorm"
	"short-vid-joy/shortrpc/shortrpc"
)

type Video struct {
	gorm.Model
	UserId        int64  `gorm:"type:int(11);not null;comment:'用户id'"`
	VideoTitle    string `gorm:"type:varchar(50);not null;comment:'标题'"`
	VideoCategory string `gorm:"type:varchar(50);not null;comment:'视频分类'"`
	VideoLink     string `gorm:"type:varchar(500);not null;comment:'视频URL'"`
	VideoImage    string `gorm:"type:varchar(500);comment:'视频封面'"`
	VideoIntro    string `gorm:"type:varchar(500);comment:'视频简介'"`
	PlayNum       int64  `gorm:"type:int(11);default:0;comment:'播放量'"`
	LikeNum       int64  `gorm:"type:int(11);default:0;comment:'点赞数'"`
	CollectNum    int64  `gorm:"type:int(11);default:0;comment:'收藏数'"`
	CommentNum    int64  `gorm:"type:int(11);default:0;comment:'评论数'"`
	VideoStatus   int    `gorm:"type:int(11);default:0;;comment:'视频状态,0-已发布，1-草稿，2-下架'"`
	TopicId       int64  `gorm:"type:int(11);default:0;comment:'话题ID'"`
}

func (v *Video) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(v).Error
}

func (v *Video) UpdateVideo(db *gorm.DB) error {
	return db.Debug().Updates(v).Error
}

func (v *Video) FindVideoById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id = ?", id).Find(v).Error
}

func (v *Video) DelVideo(db *gorm.DB, id int64) error {
	return db.Debug().Where("id = ?", id).Delete(v).Error
}

func (v *Video) VideoShow(db *gorm.DB, in *shortrpc.VideoShowRequest) shortrpc.VideoShowResponse {
	var videoShow shortrpc.VideoShowResponse
	db.Debug().Model(&Video{}).
		Select("videos.id  as video_id,videos.*,head_image,nick_name,topic_name").
		Joins("left join users on users.id=videos.user_id").
		Joins("left join topics on topics.id=videos.topic_id").
		Where("videos.user_id= ? and videos.id = ?", in.UserId, in.VideoId).
		Find(&videoShow)
	return videoShow
}

func (v *Video) UpdateVideoCollectNum(db *gorm.DB, id int64) error {
	return db.Debug().Model(&Video{}).
		Where("id = ?", id).
		Update("collect_num", gorm.Expr("collect_num + ?", 1)).
		Error
}

func (v *Video) UpdateVideoByCollectNum(db *gorm.DB, id int64) error {
	return db.Debug().Model(&Video{}).
		Where("id = ?", id).
		Update("collect_num", gorm.Expr("collect_num - ?", 1)).
		Error
}

func (v *Video) UpdateVideoPlayNum(db *gorm.DB, id int64) error {
	return db.Debug().Model(&Video{}).
		Where("id = ?", id).
		Update("play_num", gorm.Expr("play_num + ?", 1)).
		Error
}

func VideoList(db *gorm.DB, in *shortrpc.VideoListRequest, list []*shortrpc.VideoList) []*shortrpc.VideoList {
	tx := db.Debug().Model(&Video{}).
		Select("video_title,video_image,play_num,head_image,nick_name").
		Joins("left join users on users.id=videos.user_id").
		Where("videos.user_id= ?", in.UserId)

	if in.SortType == 0 {
		tx.Order("play_num desc")
	}

	if in.SortType == 1 {
		tx.Order("videos.created_at desc")
	}

	tx.Scopes(Paginate(int(in.Page), int(in.PageSize))).Find(&list)
	return list
}
